package com.boby.homecamera.activity.server

import android.annotation.SuppressLint
import android.app.ActivityOptions
import android.content.Intent
import android.graphics.SurfaceTexture
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.Surface
import android.view.TextureView
import android.view.View
import android.widget.AdapterView
import android.widget.Spinner
import android.widget.TextView
import androidx.appcompat.widget.SwitchCompat
import androidx.appcompat.widget.Toolbar
import androidx.core.view.isVisible
import com.boby.homecamera.R
import com.boby.homecamera.config.AppConfig
import com.boby.homecamera.helper.ShizukuHelper
import com.boby.homecamera.service.MainService
import com.boby.lib_common.base.BaseActivity
import com.boby.lib_common.util.NetUtils
import com.pedro.library.view.GlStreamInterface
import kotlinx.coroutines.Runnable

class ServerHomeActivity : BaseActivity() {
    private val TAG = "ServerHomeActivity"
    private lateinit var tv_ip: TextView
    private lateinit var sw_show_preview: SwitchCompat
    private lateinit var sw_show_h_flip: SwitchCompat
    private lateinit var sw_show_v_flip: SwitchCompat
    private lateinit var sp_person_orientation: Spinner
    private lateinit var tv_person_detect_orientation: TextView
    private lateinit var ttv_preview: TextureView
    private var shizukuHelper = ShizukuHelper()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sever_home)

        val toolbar: Toolbar = findViewById(R.id.mToolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(false) // 显示返回按钮
        initToolBar(toolbar)
        startServer()

        initView()
        initData()
        shizukuHelper.init()
    }

    private fun initView(){
        tv_ip = findViewById(R.id.tv_ip)
        sw_show_preview = findViewById(R.id.sw_show_preview)
        sw_show_h_flip = findViewById(R.id.sw_show_h_flip)
        sw_show_v_flip = findViewById(R.id.sw_show_v_flip)
        ttv_preview = findViewById(R.id.ttv_preview)
        tv_person_detect_orientation = findViewById(R.id.tv_person_detect_orientation)
        sp_person_orientation = findViewById(R.id.sp_person_orientation)

        ttv_preview.surfaceTextureListener = object : TextureView.SurfaceTextureListener{
            override fun onSurfaceTextureAvailable(
                surface: SurfaceTexture,
                width: Int,
                height: Int
            ) {
                Log.d(TAG,"onSurfaceTextureAvailable")
                val glInterface = MainService.recordServer?.glInterface
                if(glInterface is GlStreamInterface){
                    if(ttv_preview.isVisible && sw_show_preview.isChecked){
                        glInterface.attachPreview(Surface(surface))
                    }
                }
            }

            override fun onSurfaceTextureSizeChanged(
                surface: SurfaceTexture,
                width: Int,
                height: Int
            ) {

            }

            override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
                Log.d(TAG,"onSurfaceTextureDestroyed")
                return true
            }

            override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {

            }

        }

        sw_show_preview.setOnCheckedChangeListener { view,checked ->
            val glInterface = MainService.recordServer?.glInterface
            if(glInterface == null){
                if(checked){
                    ttv_preview.visibility = View.GONE
                    sw_show_preview.isChecked = false
                }
                return@setOnCheckedChangeListener
            }
            if(glInterface is GlStreamInterface){
                if(checked){
                    ttv_preview.visibility = View.VISIBLE
                    if(ttv_preview.surfaceTexture != null){
                        glInterface.attachPreview(Surface(ttv_preview.surfaceTexture))
                    }
                }else{
                    ttv_preview.visibility = View.GONE
                    glInterface.deAttachPreview()

                }
            }
        }

        sw_show_h_flip.setOnCheckedChangeListener { view,checked ->
            AppConfig.isFlipHorizontal = checked
            MainService.recordServer?.setCameraHorizontalFlip(checked)
        }
        sw_show_v_flip.setOnCheckedChangeListener { view,checked ->
            AppConfig.isFlipVertical = checked
            MainService.recordServer?.setCameraVerticalFlip(checked)
        }
        sp_person_orientation.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                arg0: AdapterView<*>?,
                arg1: View?,
                position: Int,
                id: Long
            ) {
                when(position){
                    0 -> AppConfig.detectOrientation = 90
                    1 -> AppConfig.detectOrientation = 270
                    2 -> AppConfig.detectOrientation = 180
                    3 -> AppConfig.detectOrientation = 0
                }
            }

            override fun onNothingSelected(arg0: AdapterView<*>?) {
            }
        })

    }

    @SuppressLint("SetTextI18n")
    private fun initData(){
        tv_ip.text = "ip:${NetUtils.getLocalIPAddress().hostAddress}"
        sw_show_v_flip.isChecked = AppConfig.isFlipVertical!!
        sw_show_h_flip.isChecked = AppConfig.isFlipHorizontal!!
        sp_person_orientation.isVisible = AppConfig.isDetectPersonEvent == true
        tv_person_detect_orientation.isVisible = AppConfig.isDetectPersonEvent == true
        val index =  when(AppConfig.detectOrientation){
            180 -> 2
            270 -> 1
            90 ->  0
            else ->  3
        }
        sp_person_orientation.setSelection(index)
    }
    private fun startServer() {
        if(!MainService.isRunning){
            val intent = Intent(this, MainService::class.java)
            startService(intent)
        }

    }

    override fun onResume() {
        super.onResume()
        screenOffDelay()
    }

    override fun onPause() {
        super.onPause()
        sw_show_preview.isChecked = false
        tv_ip.removeCallbacks(screenOffDisplay)
    }

    override fun onDestroy() {
        super.onDestroy()
        shizukuHelper.unInit()
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        screenOffDelay()
        return super.dispatchTouchEvent(ev)
    }

    fun stopServer(view: View) {

        val intent = Intent(this, MainService::class.java)
        stopService(intent)

        val option = ActivityOptions.makeCustomAnimation(this, com.boby.lib_common.R.anim.slide_in_left, com.boby.lib_common.R.anim.slide_out_right)
        startActivity(Intent(this, InitServerActivity::class.java),option.toBundle())
        finish()

    }
    private fun screenOffDelay(){
        tv_ip.removeCallbacks(screenOffDisplay)
        tv_ip.postDelayed(screenOffDisplay,30000)
    }
    private val screenOffDisplay = Runnable{
        screenOff(tv_ip)
    }

    fun screenOff(view: View) {
       val displayId =  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            display.displayId
        }else{
           windowManager.defaultDisplay.displayId
        }
        shizukuHelper.setDisplayPower(displayId,false)
    }
}